package VariantEval;

use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
 
@ISA = qw(Exporter AutoLoader);

@EXPORT = qw( readVariantEval );

use Data::Dumper;

sub readVariantEval {
	my ($dbh, $path_prefix, $suffix, $modifier, $field_list) = @_;
	open(my $fh, "$path_prefix.$suffix") || die "cannot open $path_prefix.$suffix\n";
	my %hash;
	my %RV = ();
	foreach my $ana_name (keys %{$field_list}) {
		read_analysis($dbh, $fh, $ana_name, \%RV, $modifier, $field_list->{$ana_name});	
	}
# 	read_analysis($dbh, $fh, 'Analysis Description:  	Ti\/Tv Variant Evaluator', \%RV, $modifier, $field_list);
# 	read_analysis($dbh, $fh, "Analysis Description:  	the overlap between eval and comp sites", \%RV, $modifier, $field_list);
	close $fh;
	return \%RV;
}

sub read_analysis {
	my ($dbh, $fh, $ana_name, $RV, $modifier, $field_list) = @_;
	while (<$fh>) {
		last if /^$ana_name/;
	}
	<$fh>; #skip Analysis Description line
	<$fh>; #skip empty line
#evaluation_name          comparison_name          jexl_expression          filter_name              novelty_name             ti_count                 tv_count                 ti/tv_ratio              ti_count_comp            tv_count_comp            ti/tv_ratio_standard		
	my $header_line = <$fh>;
	my @headers = split(/\s{2,}/, $header_line);
	<$fh>; #skip --------------- line
	my $value_line = <$fh>; ## only parse "called                   all"
	my @values = split(/\s{2,}/, $value_line);
	foreach my $fd (@{$field_list}) {
		my $metric_id = get_metric_id($dbh, $modifier, $fd);
		die "metric_id not found for $modifier $fd\n" unless defined($metric_id);
#		printf STDERR "$ana_name\t$fd\t$metric_id\n";
		my $fd_val = "NA";
		for (my $i=0; $i < scalar @headers; $i++) {
			if ($headers[$i] eq $fd) {
				$fd_val = $values[$i];
				last;
			}
		}
		$RV->{$metric_id}->{'value'} = $fd_val;
		$RV->{$metric_id}->{'field_name'} = $fd;
	}
}

sub get_metric_id {
	my ($dbh, $modifier, $fd) = @_;
	my $sql = "select Metric_id from MetricInfo where Field_name = \"$fd\" and Modifier = \"$modifier\"";
	return fetchrow1col1_arrayref($dbh, $sql);
}

sub fetchrow1col1_arrayref {
  my ($dbh, $sql) = @_;
  my $sh = $dbh->prepare($sql);
  $sh->execute();
  my $ary_ref = $sh->fetchrow_arrayref();
  $sh->finish();
  return $ary_ref->[0];
}

sub my_fetchall_arrayref {
  my ($dbh, $sql) = @_;
  my $sh = $dbh->prepare($sql);
  $sh->execute();
  my $ary_ref = $sh->fetchall_arrayref();
  $sh->finish();
  return $ary_ref;
}

1;

